CFLAGS += -Wall -O2 -ffreestanding -fno-builtin -nostdinc \
	-fno-leading-underscore
LDFLAGS += -dN -nostdlib
NASMFLAGS += -f elf
FASMFLAGS +=
YASMFLAGS += -f elf
CPPFLAGS +=
ASFLAGS +=

CROSS_PREFIX = i386-newos-
CC = ${CROSS_PREFIX}gcc
LD = ${CROSS_PREFIX}ld
NASM = nasm
FASM = fasm
YASM = yasm

#
# Rules for files
#
%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<

%.o: %.s
	$(AS) $(ASFLAGS) $(EXTRA_ASFLAGS) -o $@ $<

%.o: %.S
	$(CPP) $(CPPFLAGS) $< $*.tmp
	$(AS) $(ASFLAGS) -o $@ $*.tmp
	rm -f $*.tmp

%.o: %.asm
	$(YASM) $(YASMFLAGS) -o $@ $<

#
# Target
#
all: $(SUBDIRS) $(TARGET)

#
# Rules to process sub-directory
#
ifdef SUBDIRS
.PHONY: $(SUBDIRS)
$(SUBDIRS): dummy
	$(MAKE) -C $@
endif

#
# Rules to compile a set of .o files into one .o file
#
ifeq ($(TYPE),OBJECT)
$(TARGET): $(OBJS)
	$(LD) $(LDFLAGS) -r -o $@ $(OBJS) $(LIBS)
endif

#
# Rules to compile library
#
ifeq ($(TYPE),LIBRARY)
$(TARGET): $(OBJS) ar-target

.PHONY: ar-target
ar-target: $(OBJS)
	$(AR) $(EXTRA_ARFLAGS) rcs $(TARGET) $?
endif

#
# Rules to compile kernel
#
ifeq ($(TYPE),KERNEL)
$(TARGET): $(OBJS) $(LIBS)
	$(LD) $(LDFLAGS) -T $(LD_SCRIPT) -o $@ $(OBJS) $(LIBS)
	$(ASMGEN)

ifdef SYMBOL
	cp $@ $(SYMBOL)
endif
#	$(STRIP) -s $@
endif

-include Makefile.dep

SRCS = $(wildcard *.c) $(wildcard *.S) $(wildcard *.asm)

#
# Depend
#
.PHONY: depend dep
depend dep:
ifdef SUBDIRS
	@(for d in $(SUBDIRS) _ ; do \
	if [ "$$d" != "_" ] ; then $(MAKE) -C $$d depend; fi; \
	done);
endif
	rm -f Makefile.dep
	@(for d in $(SRCS) _ ; do \
	if [ "$$d" != "_" ] ; then \
	$(CPP) -M $(CPPFLAGS) $$d >> Makefile.dep; fi; \
	done);

#
# Clean up
#
.PHONY: clean
clean:
ifdef SUBDIRS
	@(for d in $(SUBDIRS) _ ; do \
	if [ "$$d" != "_" ] ; then $(MAKE) -C $$d clean; fi; \
	done);
endif
	rm -f Makefile.dep
	rm -f $(OBJS)
	rm -f $(TARGET)

.PHONY: dummy
